﻿using project.B12.Model.Enums;
using project.B12.Model.Models;
using System.Windows;

namespace project.B12.Service
{
    public partial class WorkSequence
    {

        /// <summary>
        /// 获取SIR
        /// </summary>
        /// <param name="bacteriaCNName">菌种的中文名称</param>
        /// <param name="medicineAbbreviation">药物的简称</param>
        /// <returns></returns>
        public Table_SIR GetSIR(string bacteriaCNName, string medicineAbbreviation)
        {
            //获取药物
            var Medicines = medicineRepository.QueryByAbbreviation(medicineAbbreviation);
            if (Medicines == null || Medicines.Count == 0)
            {
                return null;
            }
            var medicine = Medicines.First();

            var bacterias = bacteriaRepository.QueryByCNName(bacteriaCNName);
            if( bacterias.Count==0)
            {
                return null;
            }
            var bacteria= bacterias.First();
            string bacteriaLevelName = bacteriaRepository.QueryNamesByID(bacteria.Id, bacteria.Level);

            var sirsByMedicine= sIRRepository.QueryByMedicineId(medicine.Id);

            var sir= GetSIR(sirsByMedicine, bacteria.Level, bacteriaLevelName);
            if (sir != null)
                return sir;

            int value = (int)bacteria.Level - 1;
            while(value>=0)
            {
                BacteriaLevel level = (BacteriaLevel)value;
                string LevelName = bacteriaRepository.QueryNamesByID(bacteria.Id, level);
                var sirTemp= GetSIR(sirsByMedicine,level, LevelName);
                if( sirTemp != null )
                    return sirTemp;
                value = (int)level - 1;
            }

            return null;
        }


        private Table_SIR GetSIR(List<Table_SIR> sirsByMedicine,BacteriaLevel level, string bacteriaLevelName)
        {
            //找同等级的SIR
            var sirsByLevel = sirsByMedicine.Where(o => o.BacteriaLevel == level);
            if (sirsByLevel.Count() > 0 && sirsByLevel != null)
            {
                foreach (var item in sirsByLevel)
                {
                    string levelName = bacteriaRepository.QueryNamesByID(item.BacteriaLevelID, item.BacteriaLevel);
                    if (levelName == bacteriaLevelName)
                        return item;
                }
            }
            return null;
        }
    }
}
